package com.marveal.rabbit.task.autoconfigure;

import cn.hutool.json.JSONUtil;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import com.marveal.rabbit.task.parser.ElasticJobConfigParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
@ConditionalOnProperty(
        prefix = "elastic-job.zk",
        name = {"namespace", "serverLists"},
        matchIfMissing = false
)
@EnableConfigurationProperties(value = {JobZookeeperProperties.class})
public class JobParserAutoConfiguration {


    @Bean(initMethod = "init")
    public ZookeeperRegistryCenter registryCenter(JobZookeeperProperties jobZookeeperProperties) {
        String serverLists = jobZookeeperProperties.getServerLists();
        String namespace = jobZookeeperProperties.getNamespace();
        ZookeeperConfiguration zkConfig = new ZookeeperConfiguration(serverLists, namespace);
        zkConfig.setMaxRetries(jobZookeeperProperties.getMaxRetries());
        zkConfig.setBaseSleepTimeMilliseconds(jobZookeeperProperties.getBaseSleepTimeMilliseconds());
        zkConfig.setMaxSleepTimeMilliseconds(jobZookeeperProperties.getMaxSleepTimeMilliseconds());
        zkConfig.setSessionTimeoutMilliseconds(jobZookeeperProperties.getSessionTimeoutMilliseconds());
        zkConfig.setConnectionTimeoutMilliseconds(jobZookeeperProperties.getConnectionTimeoutMilliseconds());
        zkConfig.setDigest(jobZookeeperProperties.getDigest());

        log.info("zookeeper 注册中心配置成功, zookeeper configuration: {}", JSONUtil.toJsonStr(zkConfig));

        return new ZookeeperRegistryCenter(zkConfig);
    }

    @Bean
    public ElasticJobConfigParser elasticJobParser(
            JobZookeeperProperties jobZookeeperProperties,
            ZookeeperRegistryCenter zookeeperRegistryCenter) {
        return new ElasticJobConfigParser(jobZookeeperProperties, zookeeperRegistryCenter);
    }
}
